﻿using ISolutions.xRM.TechDays.NoteAddin.Entities;
using ISolutions.xRM.TechDays.Shared;
using Microsoft.Office.Tools.Ribbon;
using Microsoft.Xrm.Sdk.Client;
using System;
using System.IO;
using System.Reflection;
using System.ServiceModel.Description;

namespace ISolutions.xRM.TechDays.NoteAddin
{
    public partial class Ribbon
    {
        private OrganizationServiceContext context;

        private void Ribbon_Load(object sender, RibbonUIEventArgs e)
        {
            CreateOrganizationServiceContext();

            var query = context.CreateQuery<new_candidate>();
            dropDown1.Items.Clear();
            foreach (new_candidate entity in query)
            {
                var item = Factory.CreateRibbonDropDownItem();
                item.Label = entity.new_firstname + " " + entity.new_lastname;
                item.Tag = entity;
                dropDown1.Items.Add(item);
            }
        }

        private void CreateOrganizationServiceContext()
        {
            var uri = new Uri(StaticSettings.Uri);
            var clientCredentials = new ClientCredentials();
            clientCredentials.UserName.UserName = StaticSettings.Username;
            clientCredentials.UserName.Password = StaticSettings.Password;

            var serviceProxy = new OrganizationServiceProxy(uri, null, clientCredentials, null);
            serviceProxy.EnableProxyTypes(Assembly.GetAssembly(this.GetType()));

            context = new OrganizationServiceContext(serviceProxy);
        }

        private void CreateButton(object sender, RibbonControlEventArgs e)
        {
            var newCandidate = dropDown1.SelectedItem.Tag as new_candidate;

            var annotation = new Annotation
                {
                    Subject = "xRM Word Addin Note",
                    DocumentBody = GetFile(),
                    FileName = "xRM Word Addin Note.docx",
                    MimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                    ObjectId = newCandidate.ToEntityReference()
                };
            context.AddObject(annotation);
            context.SaveChanges();
        }

        private string GetFile()
        {
            string tempFilePath = System.IO.Path.GetTempFileName();
            Globals.ThisAddIn.Application.ActiveDocument.SaveAs(tempFilePath);
            Globals.ThisAddIn.Application.ActiveDocument.Close(false);
            return Convert.ToBase64String(File.ReadAllBytes(tempFilePath));
        }
    }
}
